package com.caipos.ruleNode.mqtt;

import com.caipos.actor.api.*;
import com.caipos.actor.common.data.StringUtils;
import com.caipos.actor.common.msg.KbMsg;
import com.caipos.actor.common.msg.KbMsgMetaData;
import com.caipos.ruleEngine.credentials.BasicCredentials;
import com.caipos.ruleEngine.credentials.ClientCredentials;
import com.caipos.ruleEngine.credentials.CredentialsType;
import com.caipos.ruleNode.KbAbstractExternalNode;
import com.caipos.util.JacksonUtil;
import com.caipos.util.KbNodeUtils;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.ssl.SslContext;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.SSLException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Slf4j
@RuleNode(
        type = ComponentType.EXTERNAL,
        name = "mqtt",
        configClazz = KbMqttNodeConfiguration.class,
        version = 1,
        nodeDescription = "Publish messages to the MQTT broker",
        nodeDetails = "Will publish message payload to the MQTT broker with QoS <b>AT_LEAST_ONCE</b>.",
        configDirective = "kbExternalNodeMqttConfig",
        icon = "call_split"
)
public class KbMqttNode extends KbAbstractExternalNode {

    private static final Charset UTF8 = StandardCharsets.UTF_8;

    private static final String ERROR = "error";

    protected KbMqttNodeConfiguration mqttNodeConfiguration;

    protected MqttClient mqttClient;

    @Override
    public void init(KbContext ctx, KbNodeConfiguration configuration) throws KbNodeException {
        super.init(ctx);
        this.mqttNodeConfiguration = KbNodeUtils.convert(configuration, KbMqttNodeConfiguration.class);
        try {
            this.mqttClient = initClient(ctx);
        } catch (KbNodeException e) {
            throw e;
        } catch (Exception e) {
            throw new KbNodeException(e);
        }
    }

    @Override
    public void onMsg(KbContext ctx, KbMsg msg) {
        String topic = KbNodeUtils.processPattern(this.mqttNodeConfiguration.getTopicPattern(), msg);
        var KbMsg = ackIfNeeded(ctx, msg);
        this.mqttClient.publish(topic, Unpooled.wrappedBuffer(getData(KbMsg, mqttNodeConfiguration.isParseToPlainText()).getBytes(UTF8)),
                        MqttQoS.AT_LEAST_ONCE, mqttNodeConfiguration.isRetainedMessage())
                .addListener(future -> {
                            if (future.isSuccess()) {
                                tellSuccess(ctx, KbMsg);
                            } else {
                                tellFailure(ctx, processException(KbMsg, future.cause()), future.cause());
                            }
                        }
                );
    }

    private KbMsg processException(KbMsg origMsg, Throwable e) {
        KbMsgMetaData metaData = origMsg.getMetaData().copy();
        metaData.putValue(ERROR, e.getClass() + ": " + e.getMessage());
        return origMsg.transform()
                .metaData(metaData)
                .build();
    }

    @Override
    public void destroy() {
        if (this.mqttClient != null) {
            this.mqttClient.disconnect();
        }
    }

    String getOwnerId(KbContext ctx) {
        return "Tenant[" + ctx.getTenantId().getId() + "]RuleNode[" + ctx.getSelf().getId() + "]";
    }

    protected MqttClient initClient(KbContext ctx) throws Exception {
        MqttClientConfig config = new MqttClientConfig(getSslContext());
//        config.setOwnerId(getOwnerId(ctx));
        if (!StringUtils.isEmpty(this.mqttNodeConfiguration.getClientId())) {
            config.setClientId(getClientId(ctx));
        }
        config.setCleanSession(this.mqttNodeConfiguration.isCleanSession());

        prepareMqttClientConfig(config);
        MqttClient client = getMqttClient(ctx, config);
        client.setEventLoop(ctx.getSharedEventLoop());
        Promise<MqttConnectResult> connectFuture = client.connect(this.mqttNodeConfiguration.getHost(), this.mqttNodeConfiguration.getPort());
        MqttConnectResult result;
        try {
            result = connectFuture.get(this.mqttNodeConfiguration.getConnectTimeoutSec(), TimeUnit.SECONDS);
        } catch (TimeoutException ex) {
            connectFuture.cancel(true);
            client.disconnect();
            String hostPort = this.mqttNodeConfiguration.getHost() + ":" + this.mqttNodeConfiguration.getPort();
            throw new RuntimeException(String.format("Failed to connect to MQTT broker at %s.", hostPort));
        }
        if (!result.isSuccess()) {
            connectFuture.cancel(true);
            client.disconnect();
            String hostPort = this.mqttNodeConfiguration.getHost() + ":" + this.mqttNodeConfiguration.getPort();
            throw new RuntimeException(String.format("Failed to connect to MQTT broker at %s. Result code is: %s", hostPort, result.getReturnCode()));
        }
        return client;
    }

    private String getClientId(KbContext ctx) throws KbNodeException {
        String clientId = this.mqttNodeConfiguration.isAppendClientIdSuffix() ?
                this.mqttNodeConfiguration.getClientId() + "_" + ctx.getServiceId() :
                this.mqttNodeConfiguration.getClientId();
        if (clientId.length() > 23) {
            throw new KbNodeException("Client ID is too long '" + clientId + "'. " +
                    "The length of Client ID cannot be longer than 23, but current length is " + clientId.length() + ".", true);
        }
        return clientId;
    }

    MqttClient getMqttClient(KbContext ctx, MqttClientConfig config) {
        return MqttClient.create(config, null, ctx.getExternalCallExecutor());
    }

    protected void prepareMqttClientConfig(MqttClientConfig config) {
        ClientCredentials credentials = this.mqttNodeConfiguration.getCredentials();
        if (credentials.getType() == CredentialsType.BASIC) {
            BasicCredentials basicCredentials = (BasicCredentials) credentials;
            config.setUsername(basicCredentials.getUsername());
            config.setPassword(basicCredentials.getPassword());
        }
    }

    private SslContext getSslContext() throws SSLException {
        return this.mqttNodeConfiguration.isSsl() ? this.mqttNodeConfiguration.getCredentials().initSslContext() : null;
    }

    private String getData(KbMsg KbMsg, boolean parseToPlainText) {
        if (parseToPlainText) {
            return JacksonUtil.toPlainText(KbMsg.getData());
        }
        return KbMsg.getData();
    }

//    @Override
//    public KbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws KbNodeException {
//        boolean hasChanges = false;
//        switch (fromVersion) {
//            case 0:
//                String parseToPlainText = "parseToPlainText";
//                if (!oldConfiguration.has(parseToPlainText)) {
//                    hasChanges = true;
//                    ((ObjectNode) oldConfiguration).put(parseToPlainText, false);
//                }
//                break;
//            default:
//                break;
//        }
//        return new KbPair<>(hasChanges, oldConfiguration);
//    }
}
